package com.scalar.chiptrack.finance.creditNote.actionCommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.finance.creditNote.forms.CreditNoteForm;
import com.scalar.chiptrack.finance.creditNote.dao.CreditNoteDAO;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * User: Sujan
 * Date: Apr 30, 2007
 * Time: 5:25:36 PM
 */
public class CreditNoteConfirmApproveCommand extends ActionCommand {
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HttpSession session  = request.getSession();
        User user            = (User) session.getAttribute ( SessionKeys.USER_KEY );
        CreditNoteForm creditNoteForm = ( CreditNoteForm ) form;

        HashMap errors = ( HashMap )request.getAttribute( SessionKeys.ERROR_MESSAGES );
        HashMap info = ( HashMap )request.getAttribute( SessionKeys.INFO_MESSAGES );
        DBTransaction dbTransaction = null;
        boolean success = false;
        try
        {
            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();
            CreditNoteDAO.updateCreditNote ( dbTransaction, creditNoteForm.getCreditNoteId(), creditNoteForm.getIssueDate(), creditNoteForm.getComments() );
            CreditNoteDAO.approveCreditNoteLineItems( dbTransaction, creditNoteForm, user.getUserId() );
            dbTransaction.commit();
            success = true;
            info.put ( "Credit/Debit Note=" + creditNoteForm.getCreditNoteNumber()," updated successfully" );
        }
        catch ( ScalarException e )
        {
            e.printStackTrace();
            errors.put ( "Could not approve Credit/Debit Note", null );
        }
        finally
        {
            if ( dbTransaction != null && !success )
            {
                try { dbTransaction.rollback(); } catch ( DBXException ignore ) {}
            }
        }
        request.setAttribute ( "customers", CustomerDAO.getAllCustomerNamesByUserType ( null, user ) );
        creditNoteForm.setCreditNoteNumber("");
        creditNoteForm.setNoteType("0");
        return mapping.findForward ( "search" );
    }
}
